package com.atguigu.gulimall.product.utils;

import org.springframework.beans.BeansException;
import org.springframework.cloud.openfeign.FeignContext;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * 动态获取 ioc 容器中的 bean 实例对象
 */
@Component("springContextUtil")
public class SpringContextUtil implements ApplicationContextAware {
    private static ApplicationContext context = null;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    public static <T> T getBean(String beanName) {
        return (T) context.getBean(beanName);
    }

    public static <T> T getBean(Class<T> aClass) {
        return context.getBean(aClass);
    }

    public static <T> T getFeignBean(String beanName, Class<T> tClass) {
        FeignContext feignContext = context.getBean("feignContext", FeignContext.class);
        return feignContext.getInstance(beanName, tClass);
    }

}
